<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { uploadCourseImage, getUploadSignUrl, uploadVideoToOSS, addCourse, updateCourse, getCourseById } from '../../services/api';

const router = useRouter();
const route = useRoute();
const courseId = computed(() => route.query.id);
const isEditMode = computed(() => !!courseId.value);

// 表单数据
const formData = ref({
  id: '',
  title: '',
  description: '',
  coverFile: null,
  videoFile: null,
  coverUrl: '',
  videoUrl: '',
  tags: '',
  status: 1, // 默认上线状态
  sortOrder: 0, // 默认排序权重
  creatorId: '', // 创建者ID
  teacherId: '' // 讲师ID
});

// 表单状态
const coverPreview = ref('');
const isSubmitting = ref(false);
const errorMessage = ref('');
const successMessage = ref('');

// 上传进度状态
const uploadProgress = ref(0);
const isUploading = ref(false);
const uploadFileName = ref('');

// 如果是编辑模式，加载课程数据
onMounted(async () => {
  if (isEditMode.value) {
    try {
      // 调用API获取课程详情
      const response = await getCourseById(courseId.value);
      if (response) {
        formData.value = {
          id: response.id,
          title: response.title,
          description: response.description,
          coverFile: null,
          videoFile: null,
          coverUrl: response.coverUrl,
          videoUrl: response.videoUrl,
          tags: response.tags,
          status: response.status,
          sortOrder: response.sortOrder,
          creatorId: response.creatorId,
          teacherId: response.teacherId
        };
        // 如果有封面图，设置预览
        if (response.coverUrl) {
          coverPreview.value = response.coverUrl;
        }
      } else {
        errorMessage.value = '获取课程信息失败';
      }
    } catch (error) {
      errorMessage.value = '获取课程信息失败';
      console.error(error);
    }
  }
});

// 处理封面图片上传
const handleCoverChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  if (!file.type.includes('image/')) {
    errorMessage.value = '请上传图片文件';
    return;
  }
  
  // 创建预览
  const reader = new FileReader();
  reader.onload = (e) => {
    coverPreview.value = e.target.result;
  };
  reader.readAsDataURL(file);
  
  try {
    // 调用上传API
    errorMessage.value = '';
    const imageUrl = await uploadCourseImage(file);
    formData.value.coverUrl = imageUrl; // 保存返回的图片URL
    formData.value.coverFile = file;
    successMessage.value = '封面上传成功';
    setTimeout(() => {
      successMessage.value = '';
    }, 3000);
  } catch (error) {
    errorMessage.value = error.message || '封面上传失败';
    console.error('封面上传失败:', error);
  }
};

// 处理视频文件上传
const handleVideoChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  if (!file.type.includes('video/')) {
    errorMessage.value = '请上传视频文件';
    return;
  }
  
  formData.value.videoFile = file;
  uploadFileName.value = file.name;
  
  try {
    // 开始上传流程
    isUploading.value = true;
    uploadProgress.value = 0;
    errorMessage.value = '';
    
    // 1. 获取上传签名URL
    const params = {
      filename: file.name,
      contentType: file.type
    };
    const signedUrl = await getUploadSignUrl(params);
    
    // 2. 直接上传视频到OSS，并监听进度
    const videoUrl = await uploadVideoToOSS(signedUrl, file, (percent) => {
      uploadProgress.value = percent;
    });
    
    // 3. 保存视频URL
    formData.value.videoUrl = videoUrl;
    successMessage.value = '视频上传成功';
    setTimeout(() => {
      successMessage.value = '';
    }, 3000);
  } catch (error) {
    errorMessage.value = error.message || '视频上传失败';
    console.error('视频上传失败:', error);
  } finally {
    isUploading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.title.trim()) {
    errorMessage.value = '请输入课程标题';
    return;
  }
  
  if (!isEditMode.value && !formData.value.videoUrl) {
    errorMessage.value = '请上传视频文件';
    return;
  }
  
  if (!isEditMode.value && !formData.value.coverUrl) {
    errorMessage.value = '请上传课程封面';
    return;
  }
  
  try {
    isSubmitting.value = true;
    errorMessage.value = '';
    
    // 准备提交到后端的数据
    const courseData = {
      title: formData.value.title,
      description: formData.value.description,
      coverUrl: formData.value.coverUrl,
      videoUrl: formData.value.videoUrl,
      tags: formData.value.tags,
      status: formData.value.status,
      sortOrder: formData.value.sortOrder
    };
    
    let result;
    
    // 根据是否为编辑模式调用不同的API
    if (isEditMode.value) {
      // 编辑模式，添加ID和其他必要字段
      courseData.id = formData.value.id;
      courseData.creatorId = formData.value.creatorId;
      courseData.teacherId = formData.value.teacherId;
      
      // 调用更新课程API
      result = await updateCourse(courseData);
    } else {
      // 新增模式
      result = await addCourse(courseData);
    }
    
    if (result.success) {
      successMessage.value = isEditMode.value ? '课程更新成功' : '课程创建成功';
      
      // 3秒后跳转到课程管理页面
      setTimeout(() => {
        router.push('/admin/courses');
      }, 3000);
    } else {
      errorMessage.value = result.message || '提交失败，请稍后再试';
    }
  } catch (error) {
    console.error('提交失败:', error);
    errorMessage.value = '提交失败，请稍后再试';
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<template>
  <div class="max-w-4xl mx-auto">
    <div class="flex items-center mb-6">
      <button
        @click="router.push('/admin/courses')"
        class="mr-4 text-gray-600 hover:text-gray-900 focus:outline-none"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
        </svg>
      </button>
      <h2 class="text-2xl font-bold text-gray-800">{{ isEditMode ? '编辑课程' : '上传新课程' }}</h2>
    </div>
    
    <div v-if="errorMessage" class="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
      {{ errorMessage }}
    </div>
    
    <div v-if="successMessage" class="mb-4 p-3 bg-green-100 text-green-700 rounded-md">
      {{ successMessage }}
    </div>
    
    <div class="bg-white shadow-md rounded-lg overflow-hidden">
      <div class="p-6 border-b border-gray-200">
        <h3 class="text-lg font-medium text-gray-900">课程基本信息</h3>
      </div>
      
      <form @submit.prevent="handleSubmit" class="p-6 space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="col-span-2">
            <label for="title" class="block text-sm font-medium text-gray-700 mb-1">课程标题 <span class="text-red-500">*</span></label>
            <input
              id="title"
              v-model="formData.title"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入课程标题"
              required
            />
          </div>
          
          <div class="col-span-2">
            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">课程描述</label>
            <textarea
              id="description"
              v-model="formData.description"
              rows="4"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入课程描述"
            ></textarea>
          </div>
          
          <div>
            <label for="tags" class="block text-sm font-medium text-gray-700 mb-1">标签</label>
            <input
              id="tags"
              v-model="formData.tags"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="例如：AI,播客,教程（用英文逗号分隔）"
            />
          </div>
          
          <div>
            <label for="sortOrder" class="block text-sm font-medium text-gray-700 mb-1">排序权重</label>
            <input
              id="sortOrder"
              v-model.number="formData.sortOrder"
              type="number"
              min="0"
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="数字越大排序越靠前"
            />
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
            <div class="flex space-x-4 mt-2">
              <label class="inline-flex items-center">
                <input 
                  type="radio" 
                  v-model="formData.status" 
                  :value="1" 
                  class="form-radio h-4 w-4 text-blue-600"
                />
                <span class="ml-2">上线</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="radio" 
                  v-model="formData.status" 
                  :value="0" 
                  class="form-radio h-4 w-4 text-blue-600"
                />
                <span class="ml-2">下线</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="radio" 
                  v-model="formData.status" 
                  :value="2" 
                  class="form-radio h-4 w-4 text-blue-600"
                />
                <span class="ml-2">草稿</span>
              </label>
            </div>
          </div>
        </div>
        
        <div class="border-t border-gray-200 pt-6">
          <h3 class="text-lg font-medium text-gray-900 mb-4">媒体文件</h3>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">课程封面 <span class="text-red-500">*</span></label>
              <div class="flex flex-col space-y-3">
                <div 
                  v-if="coverPreview" 
                  class="w-full h-48 bg-gray-100 rounded-md overflow-hidden"
                >
                  <img :src="coverPreview" alt="封面预览" class="w-full h-full object-cover" />
                </div>
                <div 
                  v-else 
                  class="w-full h-48 bg-gray-100 rounded-md flex items-center justify-center text-gray-400 border-2 border-dashed border-gray-300"
                >
                  <div class="text-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <p class="mt-1">无预览</p>
                  </div>
                </div>
                <label 
                  for="cover" 
                  class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md cursor-pointer hover:bg-gray-300 text-center"
                >
                  选择封面图片
                </label>
                <input
                  id="cover"
                  type="file"
                  accept="image/*"
                  class="hidden"
                  @change="handleCoverChange"
                />
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-3">视频文件 <span class="text-red-500">*</span></label>
              <div class="flex flex-col space-y-3">
                <div class="w-full h-48 bg-gray-100 rounded-md flex items-center justify-center text-gray-400 border-2 border-dashed border-gray-300">
                  <div class="text-center p-4">
                    <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
                    </svg>
                    <p class="mt-1" v-if="formData.videoFile">
                      已选择: {{ formData.videoFile.name }}
                    </p>
                    <p class="mt-1" v-else-if="isEditMode">
                      保持原视频不变
                    </p>
                    <p class="mt-1" v-else>
                      请选择视频文件
                    </p>
                  </div>
                </div>
                <label 
                  for="video" 
                  class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md cursor-pointer hover:bg-gray-300 text-center"
                  :class="{ 'opacity-50 cursor-not-allowed': isUploading }"
                  :disabled="isUploading"
                >
                  选择视频文件
                </label>
                <input
                  id="video"
                  type="file"
                  accept="video/*"
                  class="hidden"
                  @change="handleVideoChange"
                  :disabled="isUploading"
                />
                
                <!-- 上传进度显示 -->
                <div v-if="isUploading || uploadProgress > 0" class="mt-3">
                  <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-medium text-gray-700">上传进度</span>
                    <span class="text-sm font-medium text-gray-700">{{ uploadProgress }}%</span>
                  </div>
                  <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div 
                      class="bg-blue-600 h-2.5 rounded-full transition-all duration-300" 
                      :style="{ width: `${uploadProgress}%` }"
                    ></div>
                  </div>
                  <p class="mt-1 text-sm text-gray-500">
                    <span v-if="isUploading">正在上传 {{ uploadFileName }}...</span>
                    <span v-else-if="uploadProgress === 100">上传完成</span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="border-t border-gray-200 pt-6 flex justify-end space-x-3">
          <button
            type="button"
            @click="router.push('/admin/courses')"
            class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
          >
            取消
          </button>
          <button
            type="submit"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? '提交中...' : (isEditMode ? '保存修改' : '创建课程') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>